//
//  DBManger.m
//  
//
//  Created by lanou on 16/4/11.
//
//

#import "DBManger.h"

static DBManger *dbManger = nil;
@implementation DBManger

+(DBManger *)shareInstanceDbName:(NSString *)dbName {
    @synchronized(self) {
        if (dbManger == nil) {
            dbManger = [[DBManger alloc] initWithDbName:dbName];
        }
        return dbManger;
    }
}

//创建数据库存储文件路径
- (instancetype)initWithDbName:(NSString *)dbName{
    //有init都要对继承父类
    self = [super init];
    if (self) {
        if (!dbName) {//数据库名不存在
            NSLog(@"数据库创建失败");
        }else{
            //获取沙盒路径
            NSString *docuPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
            //创建数据库路径
            NSString *dbPath = [docuPath stringByAppendingPathComponent:dbName];
            //文件管理者
            NSFileManager *fileManager = [NSFileManager defaultManager];
            BOOL exist = [fileManager fileExistsAtPath:dbPath];
            if (!exist) {
                NSLog(@"创建失败:%@", dbPath);
            }else{
                NSLog(@"创建成功%@", dbPath);
            }
            //打开数据库，创建数据库
            [self openDB:dbPath];
        }
        
     }
    return self;
}

//打开数据库
- (void) openDB:(NSString *)dbPath
{
    //如果没有数据库，创建数据库
    if (!self.dateBase) {
        self.dateBase = [FMDatabase databaseWithPath:dbPath];
    }
    if (![self.dateBase open]) {
        NSLog(@"不能打开数据库");
    }
}

//关闭数据库
- (void)closeDB{
    [self.dateBase close];//数据库关闭
    dbManger = nil;
    
}

//程序推出时数据库关闭
- (void)dealloc{
    [self closeDB];
}

@end
